import types from '@/store/mutations/mutation-types';
import dao from '@/dao';
import Storage from '@/lib/storage';
import { PageKeys } from '@/lib/variable.js';
import { parseBrand, fmtBrandPageKey } from '@/lib/parse-brand';
import { Toast as VanToast } from 'vant';
import envJudge from '@/lib/judge-env.js';
const Cookies = new Storage('cookie');
const ls = new Storage('localStorage');

/*
 * 清除系统下所有的cookie
 */
const clearCookie = function () {
    Cookies.removeItem();
};


const actions = {
    loading({ commit }, value) {
        commit(types.LOADING, value !== undefined ? value : true);
    },

    /**
     * 获取当前设备信息
     */
    setUserAgent({ commit }, value) {
        let env = envJudge();
        let curUserAgent = {
            env, // 当前环境
            isApp: ['IOS', 'android'].includes(env), // 是不是App
            isWechat: env.indexOf('wx') > -1, // 是不是微信
            isMobile: env != 'pc' // 是不是手机
        };
        commit(types.META, {curUserAgent});
    },

    /**
     * 跳到登录地址
     */
    toLoginHref({ commit, dispatch, state }, payload) {
        dispatch('jsBridge/disposeBridge', {
            method: 'toLogin'
        });
    },

    /**
     * 退出 + 跳转到登录页
     */
    logout({ commit, dispatch, state }, payload) {
        clearCookie();
        dispatch('toLoginHref');
    },

    /**
     * 去登录
     */
    toLogin({ commit, dispatch, state }, payload) {
        return new Promise((resolve, reject) => {
            dispatch('proxyAction', {
                name: 'login',
                data: {
                    // auth_type: curType.value.auth_type,
                    ...payload.values
                }
            })
                .then((res) => {
                    if (res.status.code == 200) {
                        let data = res.data || {};
                        dispatch('loginSuccess', {
                            ...data,
                            keepCookie: true
                        });
                        dispatch('user/getCurrentUser');
                        resolve(data);
                    }
                })
                .catch((error) => {
                    G_dispatchEvent('toast', { message: error.status.desc, type: 'error'});
                    reject(error);
                })
                .finally(() => {});
        });
    },
    /**
     * 登录成功
     */
    loginSuccess({ state, commit, dispatch }, data) {
        return new Promise((resolve, reject) => {
            let token = data.access_token;
            if (data.keepCookie) {
                Cookies.setItem('X-DT-accessToken', {
                    value: token,
                    params: {
                        expires: 30
                    }
                });
                Cookies.setItem('is-keep-cookie', {
                    value: data.keepCookie,
                    params: {
                        expires: 30
                    }
                });
            } else {
                Cookies.setItem('X-DT-accessToken', {
                    value: token
                });
                Cookies.setItem('is-keep-cookie', {
                    value: data.keepCookie
                });
            }
            resolve();
        });
    },

    /**
     * 设置state数据
     * @param {Object}  payload {
     * 	 state属性Key: value
     * }
     */
    meta({ commit, dispatch, state }, payload) {
        commit(types.META, payload);
    },

    /**
     * 消息提示，所有的toast提示都走message，不要单独调用组件的message
     * @param {Object} payload {
     *	 msg: toast的文本内容,
     *   type: 'success' || 'loading' || 'none'   默认为 'none'
     * 	 duration: 3000 默认为3秒
     * }
     */
    message({ commit, dispatch, state }, payload) {
        commit(types.MESSAGE, payload);
    },

    /**
     * 埋点代理, 所有的埋点采用action的方式，放弃分散引用模式
     * @param {Object} payload {
     *	 name: string name(必须), 事件名
     * 	 data: object 需要追踪的数据
     * }
     */
    proxyTrack({ commit, dispatch, state }, payload) {
        // RecordData.track(payload.name, payload.data);
    },

    /**
     * 接口代理，没有特殊情况的接口都通过此方法进行代码，可覆盖大部分操作
     *
     * @param {Object} info => {
     *    name: action name(必须), 即 porter/portals.js 里的配置名称
     *    txtSuccess: 成功消息。true/字符串 显示；false/不传 不显示；
     *    txtError: 失败消息。true/字符串/不传 显示；false 不显示；
     *    queries: 请求参数 (url 问号后面的参数)
     *    data: form data 数据
     *    params: 替换portals 里的 uri 里的参数的内容
     *    uri: 替换portals里定义的 uri
     *    headers: 与 portals里定义的 headers 合并
     * }
     */
    // proxyAction({ commit, dispatch, state }, payload) {
    //     checkPortalName(payload);
    //     // 只有状态码为200的时候才会走resolve, 其他都走reject
    //     return new Promise((resolve, reject) => {
    //         dao.x(payload).then((res) => {
    //             let code = res.code || res.status?.code || res.status;
    //             if (code == 20100001) {
    //                 console.log('-----', `当前接口是:${payload}`)
    //             }
    //             let handler = ResonpseHandler[code];
    //             if (handler) {
    //                 handler(commit, dispatch, state, res, payload);
    //             }

	// 			// 状态码为 200 时走resolve, 其他情况都走reject
	// 			if(code == 200) {
    //                 if(payload.name === 'activitUserAuths' && PageKeys.includes(payload.queries.authKey)) {
    //                     let temp = res.data;
    //                     if(temp && temp.authMap && temp.authMap[payload.queries.authKey] && temp.authMap[payload.queries.authKey] != 1 || !temp.authMap || !temp.authMap[payload.queries.authKey]) {
    //                         commit('meta', {
    //                             initialized: false,
    //                             pageMessage: { 
    //                                 code: 403,
    //                                 message: '无权限访问此页面'
    //                             }
    //                         });        
    //                     }
    //                 }
    //                 resolve(res);
	// 			} else {
    //                 commitGlobalMessage(commit, res, payload);
	// 				reject(res);
	// 			}
	// 		})
	// 		.catch((err) => {
    //             commitGlobalMessage(
    //                 commit,
    //                 {
    //                     code: -1,
    //                     error: err
    //                 },
    //                 payload
    //             );
    //             reject(err);
	// 		});
    //     });
    // },

    /**
     * 更新state中的品牌相关信息
     */
    updateBrand({ commit, dispatch, state }, data) {
        let { ver, publishBrand } = data || {};
        ls.setItem('brandVer', ver);
        ls.setItem('publishBrand', publishBrand);
        let moduleList = publishBrand.brandModulesV2 || [];
        let pageMap = fmtBrandPageKey(moduleList) || {};
        ls.setItem('pagePermission', pageMap);
        commit(types.META, {
            brand: {
                ver,
                publishBrand
            },
            brandFactory: parseBrand(publishBrand, state.currentUser),
            pagePermission: pageMap
        });
    },

    /**
     * 设置站点基本信息
     */
    setSiteInfo({ commit, dispatch, state }, data) {
        let { publishBrand } = data || {};
        let { brandConfig } = publishBrand || {};

        // 设置title
        document.title = brandConfig.siteName;

        // 设置favicon
        let link =
            document.querySelector("link[rel*='icon']") ||
            document.createElement('link');
        link.type = 'image/x-icon';
        link.rel = 'shortcut icon';
        link.href = brandConfig.favicon;
        document.getElementsByTagName('head')[0].appendChild(link);

        // 设置网站描述
        if (brandConfig.brandDescription) {
            let head = document.getElementsByTagName('head');
            if (document.querySelector('meta[name="description"]')) {
                document
                    .querySelector('meta[name="description"]')
                    .setAttribute('content', brandConfig.brandDescription);
            } else {
                let metaDescription = document.createElement('meta');
                metaDescription.setAttribute('name', 'description');
                metaDescription.setAttribute(
                    'content',
                    brandConfig.brandDescription
                );
                head[0].appendChild(metaDescription);
            }
        }
    },
};

export default actions;
